package com.yinhai.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yinhai.util.AccountBean;
import com.yinhai.util.AccountMintype;
import com.yinhai.util.AccoutTypeutils;
import com.yinhai.util.DataKind;
import com.yinhai.util.ManagerContact;

public class LocalContactJoinActivity extends Activity {
	private LinearLayout phone_list, email_list, company_list, address_list,
			im_list, nickname_list, event_list, note_list;
	private LinearLayout[] contain_linears;
	private Button addButton;
	private EditText contact_name;
	private ImageButton ib_commit;
	private TextView tv_title;
	private TextView tv_groupcontent; 
	
	private Context context;

	private String[] names;
	private LayoutInflater inflater;
	private Map<Integer, List<DataKind>> results = new HashMap<Integer, List<DataKind>>();
	//
//	private String phonenumber;
	private String username;
	private int pagetype;// 0代表新增和修改，1代表详情
	
	private CharSequence[] groups;
	
	private String flag;
	private String main_contacts_name;
	private String contacts_rawId_list;
	private String contacts_phone_list;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_local_contact_add);
		context = this;
		flag = this.getIntent().getStringExtra("flag");
		main_contacts_name = this.getIntent().getStringExtra("main_contacts_name");
		contacts_rawId_list = this.getIntent().getStringExtra("contacts_rawId_list");
		contacts_phone_list = this.getIntent().getStringExtra("contacts_phone_list");
		this.getIntent().getStringExtra("");
		this.getIntent().getStringExtra("");
		phone_list = (LinearLayout) this.findViewById(R.id.phone_list);
		email_list = (LinearLayout) this.findViewById(R.id.email_list);
		company_list = (LinearLayout) this.findViewById(R.id.company_list);
		address_list = (LinearLayout) this.findViewById(R.id.address_list);
		im_list = (LinearLayout) this.findViewById(R.id.im_list);
		nickname_list = (LinearLayout) this.findViewById(R.id.nickname_list);
		event_list = (LinearLayout) this.findViewById(R.id.event_list);
		note_list = (LinearLayout) this.findViewById(R.id.note_list);
		addButton = (Button) this.findViewById(R.id.label_add);
		contact_name = (EditText) findViewById(R.id.contact_name);
		ib_commit = (ImageButton) findViewById(R.id.ib_commit);
		tv_title=(TextView) findViewById(R.id.tv_title);
		tv_groupcontent= (TextView) findViewById(R.id.tv_groupcontent);

		contain_linears = new LinearLayout[] { phone_list, email_list, im_list,
				address_list, company_list, nickname_list, event_list,
				note_list };

		pagetype = getIntent().getIntExtra("pagetype", 0);
//		phonenumber = getIntent().getStringExtra("phone");
		inflater = LayoutInflater.from(context);
		
//		if (pagetype == 1) {// 详细
			addButton.setVisibility(View.GONE);
			tv_title.setText(getString(R.string.contact_detail_title));
//			results = ManagerContact.query(context, phonenumber);
			results = new HashMap<Integer,List<DataKind>>();
			List<DataKind> names1 = new ArrayList<DataKind>();
			DataKind name = new DataKind("mintype=vnd.android.cursor.item/name","姓名",main_contacts_name,0);
			names1.add(name);
			results.put(0, names1);
			List<DataKind> phones = new ArrayList<DataKind>();
			String[] phoneArray = contacts_phone_list.split(",");
			
			if("0".equals(flag)) {
				for(String phone:phoneArray) {
					phones.add(new DataKind("mintype=vnd.android.cursor.item/phone_v2","手机",phone,2));
				}
			} else {
				if(phoneArray.length > 0) {
					phones.add(new DataKind("mintype=vnd.android.cursor.item/phone_v2","手机",phoneArray[0],2));
				}
 			}
			
			results.put(1, phones);
			results.put(2, new ArrayList<DataKind>());
			results.put(3, new ArrayList<DataKind>());
			results.put(4, new ArrayList<DataKind>());
			results.put(5, new ArrayList<DataKind>());
			results.put(6, new ArrayList<DataKind>());
			results.put(7, new ArrayList<DataKind>());
			results.put(8, new ArrayList<DataKind>());
			List<DataKind> groups  = new ArrayList<DataKind>();
			DataKind group = new DataKind("mintype=vnd.android.cursor.item/group_membership","分组","所有联系人",1);
			groups.add(group);
			results.put(9, groups);
			results.put(10, new ArrayList<DataKind>());
			ib_commit.setBackgroundResource(R.drawable.dial_dialog_record);

			for (int i = 0; i < results.size(); i++) {
				List<DataKind> dataKinds = results.get(i);
				if (dataKinds != null) {
					switch (i) {
					// name
					case 0:
						username = results.get(i).get(0).getValue();
						contact_name.setText(username);
						contact_name.setEnabled(false);
						break;
					// phone
					case 1:
						// email
					case 2:

						// ime
					case 3:

						// addr
					case 4:

						// birth
					case 6:
						// orgize
					case 5:
						// nick
					case 7:
						// bak

					case 8:
						common(dataKinds, i);
						break;

					default:
						break;
					}

				}
			}
//		}
		addButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Builder dialog = new AlertDialog.Builder(context);
				dialog.setItems(names, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							inflateitem(phone_list, which,
									R.string.mn_contact_label_phone_hint);// 电话
							break;
						case 1:
							inflateitem(email_list, which,
									R.string.mn_contact_label_email_hint);// 邮箱
							break;
						case 2:
							inflateitem(im_list, which,
									R.string.mn_contact_label_im_hint);// IM
							break;
						case 3:
							inflateitem(address_list, which,
									R.string.mn_contact_label_address_hint);// 地址
							break;
						case 4:
							inflateitem(company_list, which,
									R.string.mn_contact_label_company_hint);// 公司
							break;
						case 5:
							inflateitem(nickname_list, which,
									R.string.mn_contact_label_nickname_hint);// 昵称
							break;
						case 6:
							inflateitem(event_list, which,
									R.string.mn_contact_label_event_hint);// 生日
							break;
						case 7:
							inflateitem(note_list, which,
									R.string.mn_contact_label_note_hint);// 备注
							break;

						default:
							break;
						}

					}
				}).setTitle("选择属性");
				dialog.create();
				dialog.show();

			}

		});
		updateView();
		names = getResources().getStringArray(R.array.contact_label_menu_add);
	}

	private void common(List<DataKind> dataKinds, int i) {
		for (int j = 0; j < dataKinds.size(); j++) {
			inflateitem_detail(contain_linears[i - 1], i - 1, dataKinds.get(j));
		}
	}
	
	private void inflateitem_detail(final LinearLayout ll, int which,
			DataKind dataKind) {
		LinearLayout l = (LinearLayout) inflater.inflate(
				R.layout.local_contact_add_item, null);
		EditText et_content = (EditText) l.findViewById(R.id.et_content);
		TextView tv = (TextView) l.findViewById(R.id.tv_type);
		ImageView iv_delete = (ImageView) l.findViewById(R.id.iv_delete);
		iv_delete.setVisibility(View.INVISIBLE);
		l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
		et_content.setEnabled(false);
		iv_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ll.removeView((View) (arg0.getParent().getParent().getParent()));
			}
		});
		switch (which) {
		case 0:
			getType(l,
					AccoutTypeutils.getPhoneList(LocalContactJoinActivity.this));
			break;
		case 1:
			getType(l,
					AccoutTypeutils.getEmailList(LocalContactJoinActivity.this));
			break;
		case 2:
			getType(l, AccoutTypeutils.getIMList(LocalContactJoinActivity.this));
			break;
		case 3:
			getType(l,
					AccoutTypeutils.getAddrList(LocalContactJoinActivity.this));
			break;
		case 4:
			((TextView) l.findViewById(R.id.tv_type)).setText("公司");
			l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
			break;
		case 5:
			((TextView) l.findViewById(R.id.tv_type)).setText("昵称");
			l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
			break;
		case 6:
			getType(l,
					AccoutTypeutils.getBirthday(LocalContactJoinActivity.this));
			break;
		case 7:
			((TextView) l.findViewById(R.id.tv_type)).setText("备注");
			l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
			break;

		default:
			break;
		}
		if(!TextUtils.isEmpty(dataKind.getLable()))
		tv.setText(dataKind.getLable() + "");
		
		et_content.setText(dataKind.getValue());
		
		ll.addView(l);
	}

	private void inflateitem(final LinearLayout ll, int which, int hintid) {
		LinearLayout l = (LinearLayout) inflater.inflate(
				R.layout.local_contact_add_item, null);
		ImageView iv_delete = (ImageView) l.findViewById(R.id.iv_delete);
		EditText et_content = (EditText) l.findViewById(R.id.et_content);
		et_content.setHint(hintid);
		et_content.requestFocus();
		// iv_delete.setTag(phonecount);
		iv_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ll.removeView((View) (arg0.getParent().getParent().getParent()));
			}
		});
		switch (which) {
		case 0:
			getType(l,
					AccoutTypeutils.getPhoneList(LocalContactJoinActivity.this));
			break;
		case 1:
			getType(l,
					AccoutTypeutils.getEmailList(LocalContactJoinActivity.this));
			break;
		case 2:
			getType(l, AccoutTypeutils.getIMList(LocalContactJoinActivity.this));
			break;
		case 3:
			getType(l,
					AccoutTypeutils.getAddrList(LocalContactJoinActivity.this));
			break;
		case 4:
			l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
			getType(l,
					AccoutTypeutils.getOrgnization(LocalContactJoinActivity.this));
			break;
		case 5:
			l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
			getType(l,
					AccoutTypeutils.getNickName(LocalContactJoinActivity.this));
			break;
		case 6:
			getType(l,
					AccoutTypeutils.getBirthday(LocalContactJoinActivity.this));
			break;
		case 7:
			l.findViewById(R.id.iv_down).setVisibility(View.INVISIBLE);
			getType(l,
					AccoutTypeutils.getBak(LocalContactJoinActivity.this));
			break;

		default:
			break;
		}
		ll.addView(l);
	}

	private void getType(LinearLayout l, final List<DataKind> datakind_list) {
		final TextView tv = (TextView) l.findViewById(R.id.tv_type);
		tv.setText(datakind_list.get(0).getValue());
		tv.setTag(datakind_list.get(0).getData2());
		View ll_type = l.findViewById(R.id.ll_type);
		if(pagetype==1)
		ll_type.setEnabled(false);
		ll_type.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Builder dialog = new AlertDialog.Builder(context);
				dialog.setItems(getTypeArray(datakind_list),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								DataKind result = datakind_list.get(which);
								tv.setText(result.getValue());
								tv.setTag(datakind_list.get(which).getData2());
								dialog.dismiss();
							}
						});
				dialog.create();
				dialog.show();

			}


		});
	}

	private CharSequence[] getTypeArray(List<DataKind> phoneList) {
		String[] array = new String[phoneList.size()];
		for (int i = 0; i < phoneList.size(); i++) {
			array[i] = phoneList.get(i).getValue();
		}
		return array;
	}
	
	public void onBack(View view) {
		finish();
	}

	public void onCommit(View view) {
		String contact_name_str = contact_name.getText().toString().trim();
		if (TextUtils.isEmpty(contact_name_str)) {
			Toast.makeText(this, "请输入联系人名字", Toast.LENGTH_SHORT).show();
			contact_name.requestFocus();
			return;
		}

		results.clear();
		List<DataKind> dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < phone_list.getChildCount(); i++) {
			TextView tv_type = (TextView) phone_list.findViewById(R.id.tv_type);
			EditText et_content = (EditText) phone_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.PHONE, content,
						Integer.parseInt(tv_type.getTag().toString()));
				dataKinds.add(dataKind);
			}
		}
		results.put(0, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < email_list.getChildCount(); i++) {
			TextView tv_type = (TextView) email_list.findViewById(R.id.tv_type);
			EditText et_content = (EditText) email_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.EMAIL, content,
						Integer.parseInt(tv_type.getTag().toString()));
				dataKinds.add(dataKind);
			}
		}
		results.put(1, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < im_list.getChildCount(); i++) {
			TextView tv_type = (TextView) im_list.findViewById(R.id.tv_type);
			EditText et_content = (EditText) im_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.IM, content,
						Integer.parseInt(tv_type.getTag().toString()));
				dataKinds.add(dataKind);
			}
		}
		results.put(2, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < address_list.getChildCount(); i++) {
			TextView tv_type = (TextView) address_list
					.findViewById(R.id.tv_type);
			EditText et_content = (EditText) address_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.ADDR, content,
						Integer.parseInt(tv_type.getTag().toString()));
				dataKinds.add(dataKind);
			}
		}
		results.put(3, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < company_list.getChildCount(); i++) {
			EditText et_content = (EditText) company_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.organization,
						content, 0);
				dataKinds.add(dataKind);
			}
		}
		results.put(4, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < nickname_list.getChildCount(); i++) {
			EditText et_content = (EditText) nickname_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.nickname,
						content, 0);
				dataKinds.add(dataKind);
			}
		}
		results.put(5, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < event_list.getChildCount(); i++) {
			TextView tv_type = (TextView) event_list.findViewById(R.id.tv_type);
			EditText et_content = (EditText) event_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.identity,
						content, Integer.parseInt(tv_type.getTag().toString()));
				dataKinds.add(dataKind);
			}
		}
		results.put(6, dataKinds);

		dataKinds = new ArrayList<DataKind>();
		for (int i = 0; i < note_list.getChildCount(); i++) {
			EditText et_content = (EditText) note_list
					.findViewById(R.id.et_content);
			String content = et_content.getText().toString().trim();
			if (!TextUtils.isEmpty(content)) {
				DataKind dataKind = new DataKind(AccountMintype.BAK, content, 0);
				dataKinds.add(dataKind);
			}
		}
		results.put(7, dataKinds);
		
		//分组
		dataKinds = new ArrayList<DataKind>();
		if(selecteds!=null){
		for (int i = 0; i < selecteds.length; i++) {
			if(selecteds[i]){
				DataKind dataKind = new DataKind(AccountMintype.GROUP, groups[i].toString(), 0);
				dataKinds.add(dataKind);
			}
		}
		results.put(AccountBean.A_GROUP, dataKinds);
		}
		
		try {
			ManagerContact.deleteRawContacts(context,contacts_rawId_list.split(","));
			ManagerContact.InsertContact(context, contact_name_str, results);
			Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
			Intent imgroupBroadcast = new Intent("com.clearsamecontact.update");
			sendBroadcast(imgroupBroadcast);
			finish();
		} catch (Exception e) {
			Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}

	private void updateView() {
		addButton.setVisibility(View.VISIBLE);
		tv_title.setText(getString(R.string.contact_add_title));
		// results = ManagerContact.query(context, phonenumber);
		ib_commit.setBackgroundResource(R.drawable.title_02);

		for (int i = 0; i < contain_linears.length; i++) {
			for (int j = 0; j < contain_linears[i].getChildCount(); j++) {
				contain_linears[i].findViewById(R.id.iv_delete).setVisibility(
						View.VISIBLE);
				EditText et_content = (EditText) contain_linears[i]
						.findViewById(R.id.et_content);
				contain_linears[i].findViewById(R.id.iv_down).setVisibility(
						View.VISIBLE);
				et_content.setEnabled(true);
				contain_linears[i].findViewById(R.id.ll_type).setEnabled(true);
			}

		}
		contact_name.setEnabled(true);
		// LL_all.invalidate();
	}
	
	//分组
	private boolean[] selecteds;
	  public void group(View view){
		  groups=getTypeArray(AccoutTypeutils.getGroups(context));
		  selecteds=new boolean[groups.length];
		    	Builder   dialog  = new AlertDialog.Builder(this);
		    	dialog.setTitle("分组设置");
		    	 DialogInterface.OnMultiChoiceClickListener mutiListener =   
		                 new DialogInterface.OnMultiChoiceClickListener() {  
		                       
		                     @Override  
		                     public void onClick(DialogInterface dialogInterface,   
		                             int which, boolean isChecked) {  
		                    	 selecteds[which] = isChecked;  
		                     }  
		                 };  
		    	
		                 dialog.setMultiChoiceItems(groups, selecteds, mutiListener);  
		                 DialogInterface.OnClickListener btnListener =   
		                     new DialogInterface.OnClickListener() {  
		                         @Override  
		                         public void onClick(DialogInterface dialogInterface, int which) {  
		                        	 String selectedStr = ""; 
		                             for(int i=0; i<selecteds.length; i++) {  
		                                 if(selecteds[i] == true) {  
		                                     selectedStr = selectedStr + " ; " +  groups[i];
		                                 }  
		                             }
		                             tv_groupcontent.setText(selectedStr);
		                         }  
		                     };  
		                 dialog.setPositiveButton("确定", btnListener)
		                 .setNegativeButton("取消", null);  
		                 dialog.create();
		    	
		    	
		    	dialog.show();
		    }
}
